package com.make.sunflower.controller;


import com.make.sunflower.common.Result;
import com.make.sunflower.entity.User;
import com.make.sunflower.service.impl.UserService;
import com.make.sunflower.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenjiaxin
 * @since 2022-02-26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/list")
    public Result<List<User>> list(){
        return Result.success(userService.list());
    }

    @GetMapping("/detail")
    public Result<User> detail(@RequestParam("user_id") Long userId){
        /*尝试从缓存中获取*/
        User user = (User)redisUtil.get(String.valueOf(userId));
        if (user != null){
            return Result.success(user);
        }
        user = userService.getById(userId);
        if (user != null){
            redisUtil.set(String.valueOf(userId), user,3000);
        }
        return Result.success(user);
    }

    @PostMapping("/register")
    public Result<User> register(@RequestBody @Validated User user){
        return Result.success(userService.register(user));
    }
}

